/*
 * 使用PWM来驱动舵机
 * 舵机有五个，分别控制四肢和尾巴
 * TIM2来驱动四肢，TIM3来驱动尾巴
 * 舵机对应的gpio口: 左前->PA0, 左后->PA2, 右前->PA1, 右后->PA3, 尾巴->PA6
*/
#include "stm32f10x.h"                  // Device header

#include "PWM.h"
#include "stm32f10x_rcc.h"
#include "stm32f10x_gpio.h"
#include "stm32f10x_tim.h"

/*
 * 舵机要求的周期是20ms,频率就是 1 / 20ms = 50HZ
 * pwm freq = 72MHZ / (PSC + 1) / (ARR + 1)
*/

void pwm_init(void)
{
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);

    GPIO_InitTypeDef GPIO_InitStructer;
    GPIO_InitStructer.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1 | GPIO_Pin_2 | GPIO_Pin_3 | GPIO_Pin_6;
    GPIO_InitStructer.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_InitStructer.GPIO_Mode = GPIO_Mode_AF_PP;
    GPIO_Init(GPIOA, &GPIO_InitStructer);

    TIM_InternalClockConfig(TIM2);
    TIM_InternalClockConfig(TIM3);

    TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructer;
    TIM_TimeBaseInitStructer.TIM_Prescaler = 72 - 1;              //PSC
    TIM_TimeBaseInitStructer.TIM_CounterMode = TIM_CounterMode_Up;
    TIM_TimeBaseInitStructer.TIM_Period = 20000 - 1;                //ARR
    TIM_TimeBaseInitStructer.TIM_ClockDivision = TIM_CKD_DIV1;
    TIM_TimeBaseInitStructer.TIM_RepetitionCounter = 0;
    TIM_TimeBaseInit(TIM2, &TIM_TimeBaseInitStructer);
    TIM_TimeBaseInit(TIM3, &TIM_TimeBaseInitStructer);

    TIM_OCInitTypeDef TIM_OCInitStructer;
    TIM_OCStructInit(&TIM_OCInitStructer);
    TIM_OCInitStructer.TIM_OCMode = TIM_OCMode_PWM1;
    TIM_OCInitStructer.TIM_OutputState = TIM_OutputState_Enable;
    TIM_OCInitStructer.TIM_Pulse = 0;                               //CCR
    TIM_OCInitStructer.TIM_OCPolarity = TIM_OCPolarity_High;
    TIM_OC1Init(TIM2, &TIM_OCInitStructer);
    TIM_OC2Init(TIM2, &TIM_OCInitStructer);
    TIM_OC3Init(TIM2, &TIM_OCInitStructer);
    TIM_OC4Init(TIM2, &TIM_OCInitStructer);
    TIM_OC1Init(TIM3, &TIM_OCInitStructer);

    TIM_Cmd(TIM2, ENABLE);
    TIM_Cmd(TIM3, ENABLE);
}

void pwm_set_compare_left_up(uint16_t Compare1) //左前
{
    TIM_SetCompare1(TIM2, Compare1);
}

void pwm_set_compare_light_up(uint16_t Compare2) //右前
{
    TIM_SetCompare2(TIM2, Compare2);
}

void pwm_set_compare_left_dowm(uint16_t Compare3) //左后
{
    TIM_SetCompare3(TIM2, Compare3);
}

void pwm_set_compare_light_dowm(uint16_t Compare4) //右后
{
    TIM_SetCompare4(TIM2, Compare4);
}

void pwm_set_compare_w(uint16_t Compare1) //尾巴
{
    TIM_SetCompare1(TIM3, Compare1);
}
